package com.alogic.xscript.plugins;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;

/**
 * 递归调用
 *
 * @since 1.6.13.6 [20200629 duanyy] <br>
 */
public class Recurse extends Segment {
    protected static final String DEFAULT_ID = "$recurse";
    protected String $id = DEFAULT_ID;

    public Recurse(String tag, Logiclet p) {
        super(tag, p);

        registerModule("recurse-iterator",Iter.class);
    }

    @Override
    public void configure(Properties p) {
        super.configure(p);
        $id = PropertiesConstants.getRaw(p, "id", $id);
    }

    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        String id = PropertiesConstants.transform(ctx,$id,DEFAULT_ID);
        try {
            ctx.setObject($id, this);
            super.onExecute(root,current,ctx,watcher);
        }finally{
            ctx.removeObject($id);
        }
    }

    /**
     * 迭代
     */
    public static class Iter extends AbstractLogiclet {
        protected String $pid = DEFAULT_ID;

        public Iter(String tag, Logiclet p) {
            super(tag, p);
        }

        @Override
        public void configure(Properties p){
            super.configure(p);
            $pid = PropertiesConstants.getRaw(p,"pid",$pid);
        }

        @Override
        protected void onExecute(XsObject root,XsObject current,LogicletContext ctx, ExecuteWatcher watcher) {
            Logiclet callback = ctx.getObject(PropertiesConstants.transform(ctx,$pid,DEFAULT_ID));
            if (callback != null){
                callback.execute(root, current, ctx, watcher);
            }
        }
    }
}